/**
 * 20170413 邱晨
 */
var queryData = {};
var urlDept = window.rootPath + '/ui/contractTotalInfo/getDeptChart';
var urlArea = window.rootPath + '/ui/contractTotalInfo/getAreaChart';
var urlIndustry = window.rootPath + '/ui/contractTotalInfo/getIndustryChart';
var urlMyTrend = window.rootPath + '/ui/contractTotalInfo/getTrendChart';
var urlContractType = window.rootPath + '/ui/contractTotalInfo/getContractTypeChart';
var urlsum = window.rootPath+ '/ui/contractviewindex/getPageSum?type=1';
var urlDeptContract =  window.rootPath+ '/ui/contractTotalInfo/getDeptContractChart';
var myDeptChart;
var myAreaChart;
var myIndustryChart;
var myTrendChart;
var myContractTypeChart;


var nowSelectDept;
jQuery(function() {	
	//查询按钮
	initQueryParam();
	jQuery("#queryBtn").on('click',function(){
		queryAllChart();
	})
	//还原按钮
	jQuery("#datehy").on('click',function(){
		var mydate = new Date();
		var begindate = mydate.getFullYear()+"-01-01"
		var enddate = "" + mydate.getFullYear() + "-";
		enddate += ((mydate.getMonth()+1)<10 ? '0'+(mydate.getMonth()+1) : (mydate.getMonth()+1)) + "-";
		enddate += (mydate.getDate()<10 ? '0'+mydate.getDate() : mydate.getDate());
		jQuery("#beginDate").val(begindate);
		$('#endDate').val(getDay(1));
		
		queryAllChart();
		   
	})
    
	myDeptChart = echarts.init(document.getElementById('deptDiv'));//部门柱状图
	myAreaChart = echarts.init(document.getElementById('areaDiv'));//片区饼图
	myContractDeptTypeChart = echarts.init(document.getElementById('lxfx'));//按部门赛选合同类型分析
	myIndustryChart = echarts.init(document.getElementById('industryDiv'));//行业饼图
	myIndustryTotalChart = echarts.init(document.getElementById('hyfx'));//总体行业柱状图
	myTrendChart = echarts.init(document.getElementById('trendDiv'));//趋势图
	myContractTypeChart = echarts.init(document.getElementById('contractTypeDiv'));//合同类型饼图
	
	//部分分析
    myDeptChart.setOption({
        title: {
            text: '部门分析'
        },
        tooltip: {},
        legend: {
            data:['销售额(元)']
        },
        xAxis: {
            data: []
        },
        yAxis: {
        	 
        },
        itemStyle : {
        	normal: {
        		show: true, 
        		position: 'top',
        		color: function(params) {
                    var colorList = [
                       '#FF3333','#00c0ef'
                       ];
                    return colorList[params.dataIndex%2]
                },
        	}
        },
        series: [{
            name: '销售额(元)',
            type: 'bar',
            barWidth : 50,
            data: [],
            itemStyle: {  
                normal: {  
                    label: {  
                        show: true,//是否展示  
                        position: 'top',
                        textStyle: {  
                            fontWeight:'bolder',  
                            fontSize : '12',  
                            fontFamily : '微软雅黑',  
                        }  
                    }  
                }  
            }, 
        }],

    });
    
    //部门图表单击
    myDeptChart.on('click', function (params) {
    	queryData.beginDate = jQuery('#beginDate').val();
    	queryData.endDate = jQuery('#endDate').val();
    	queryData.dateTimeType = jQuery('#dateTimeType').val();
    	queryData.upDeptName = params.name;
    	nowSelectDept = params.name;
    	jQuery.ajax({
			url : encodeURI(urlArea),
			type : 'get',
			data : queryData,
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				// 指定图表的配置项和数据
				myAreaChart.setOption({
			        series: [{
			              name: '销售额',
			              type: 'pie',
			              radius: '55%',
			              data:data.data
			        }]
			    });
			}
		});
    	
    	//合同类型
    	jQuery.ajax({
			url : encodeURI(urlDeptContract),
			type : 'get',
			data : queryData,
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				// 指定图表的配置项和数据
				myContractDeptTypeChart.setOption({
			        series: [{
			              name: '销售额',
			              type: 'pie',
			              radius: '55%',
			              data:data.data
			        }]
			    });
			}
		});
    });
    
    //双击部门图表打开
    myDeptChart.on('dblclick',function(params){
    	openContractList(1,params.name);
    });
    //按部门合同类型分析
    myContractDeptTypeChart.setOption({
        title: {
            text: '合同类型分析（部门）'
        },
        tooltip: {},
        series : [{
              name: '销售额',
              type: 'pie',
              radius: '55%',
              data:[],
              itemStyle:{ 
                  normal:{ 
                        label:{ 
                          show: true, 
                          formatter: '{b} : {d}%' 
                        }, 
                        labelLine :{show:true} 
                      } 
                  } 
        }]
    });
    //单击合同类型分析
    myContractDeptTypeChart.on('click',function(params){
    	//openContractList(2,nowSelectDept,params.name);
    	openContractList(6,nowSelectDept,params.name);
    });
    //片区分析
    myAreaChart.setOption({
        title: {
            text: '片区分析（部门）',
            padding: 10,
        },
        tooltip: {},
        series : [{
              name: '销售额',
              type: 'pie',
              radius: '55%',
              data:[],
              itemStyle:{ 
                  normal:{ 
                        label:{ 
                          show: true, 
                          formatter: '{b} : {d}%' 
                        }, 
                        labelLine :{show:true} 
                      } 
                  } 
        }]
    });
    
    //单击片区图表打开
    myAreaChart.on('click',function(params){
    	openContractList(2,nowSelectDept,params.name);
    });
    
    //行业分析
    myIndustryChart.setOption({
        title: {
            text: '行业分析'
        },
        tooltip: {},
        legend: {
            data:['销售额(元)']
        },
        xAxis: {
            data: []
        },
        yAxis: {},
        itemStyle : {
        	normal: {
        		color: function(params) {
        			var colorList = [
                       '#FF3333','#00c0ef'
                       ];
                    return colorList[params.dataIndex%2]
                },
        	}
        },
        series: [{
            name: '销售额(元)',
            type: 'bar',
            barWidth : 50,
            data: [],
            itemStyle: {  
                normal: {  
                    label: {  
                        show: true,//是否展示  
                        position: 'top',
                        textStyle: {  
                            fontWeight:'bolder',  
                            fontSize : '12',  
                            fontFamily : '微软雅黑',  
                        }  
                    }  
                }  
            },
        }]
    });
    
    //单击行业图表打开
    myIndustryChart.on('click',function(params){
    	openContractList(3,params.name);
    });
    //总体行业分析，不随时间的变化改变
    myIndustryTotalChart.setOption({
        title: {
            text: '历年行业分析'
        },
        tooltip: {},
        legend: {
            data:['销售额(元)']
        },
        xAxis: {
            data: []
        },
        yAxis: {},
        itemStyle : {
        	normal: {
        		color: function(params) {
        			var colorList = [
                       '#FF3333','#00c0ef'
                       ];
                    return colorList[params.dataIndex%2]
                },
        	}
        },
        series: [{
            name: '销售额(元)',
            type: 'bar',
            barWidth : 50,
            data: [],
            itemStyle: {  
                normal: {  
                    label: {  
                        show: true,//是否展示  
                        position: 'top',
                        textStyle: {  
                            fontWeight:'bolder',  
                            fontSize : '12',  
                            fontFamily : '微软雅黑',  
                        }  
                    }  
                }  
            },
        }]
    });
    //总体行业单击
    myIndustryTotalChart.on('click',function(params){
    	openContractList(3,params.name);
    });
    //趋势分析
    myTrendChart.setOption({
        title : {
            text: '趋势分析'
        },
        tooltip : {
            trigger: 'axis'
        },
        legend: {
            data:['合同金额']
        },
        toolbox: {
            show : true,
//            feature : {
//                mark : {show: true}
//                //dataView : {show: true, readOnly: false},
//                //magicType : {show: true, type: ['line', 'bar']}
//                //restore : {show: true},
//                //saveAsImage : {show: true}
//            }
        },
        calculable : true,
        xAxis : [
            {
                type : 'category',
                boundaryGap : false,
                data : []
            }
        ],
        yAxis : [
            {
                type : 'value',
                axisLabel : {
                    formatter: '{value}'
                }
            }
        ],
        series : [
            {
                name:'合同金额',
                type:'line',
                data:[],
                markLine : {
                    data : [
                        {type : 'average', name: '平均值'}
                    ]
                }
            }
        ]
    });
    
    //单击趋势图表打开
    myTrendChart.on('click',function(params){
    	openContractList(4,params.name);
    });
    
    //合同类型分析
    myContractTypeChart.setOption({
        title: {
            text: '合同类型分析（总）',
            padding: 10,
        },
        tooltip: {},
        series : [{
              name: '销售额',
              type: 'pie',
              radius: '55%',
              data:[],
              itemStyle:{ 
                  normal:{ 
                        label:{ 
                          show: true, 
                          formatter: '{b} : {d}%' 
                        }, 
                        labelLine :{show:true} 
                      } 
                  } 
        }]
    });
    
    //单击趋势图表打开
    myContractTypeChart.on('click',function(params){
    	openContractList(6,params.name);
    });
    
    //初始化加载一次非片区报表
    queryAllChart();
})

//初始化查询条件
function initQueryParam(){
	//$('#endDate').val(new Date().getFullYear()+"-"+((new Date().getMonth() + 1+"").length == 1 ? ("0"+(new Date().getMonth() + 1)) : new Date().getMonth() + 1) +"-"+new Date().getDate());
	//$('#endDate').val(new Date().getFullYear()+"-"+((new Date().getMonth() + 1+"").length == 1 ? ("0"+(new Date().getMonth() + 1)) : new Date().getMonth() + 1) +"-"+((new Date().getDate()+"").length == 1 ? ("0"+new Date().getDate()) : new Date().getDate()));
	$('#endDate').val(getDay(1));
	$('#beginDate').val(new Date().getFullYear()+"-01-01");
}
function getDay(day){  
    var today = new Date();  
      
    var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;          

    today.setTime(targetday_milliseconds); //注意，这行是关键代码    
      
    var tYear = today.getFullYear();  
    var tMonth = today.getMonth();  
    var tDate = today.getDate();  
    tMonth = doHandleMonth(tMonth + 1);  
    tDate = doHandleMonth(tDate);  
    return tYear+"-"+tMonth+"-"+tDate;  
}  
function doHandleMonth(month){  
    var m = month;  
    if(month.toString().length == 1){  
       m = "0" + month;  
    }  
    return m;  
}  

//查询图标非片区
function queryAllChart(){
	queryData.beginDate = jQuery('#beginDate').val();
	queryData.endDate = jQuery('#endDate').val();
	queryData.dateTimeType = jQuery('#dateTimeType').val();
	if(jQuery('#beginDate').val() == ""){
		alert("查询开始时间不能为空!");
		return;
	}
	if(jQuery('#endDate').val() == ""){
		alert("查询结束时间不能为空!");
		return;
	}
	jQuery.ajax({
		url : encodeURI(urlDept),
		type : 'get',
		data:queryData,
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			// 指定图表的配置项和数据
			myDeptChart.setOption({
		        xAxis: {
		            data: data.Axis
		        },
		        series: [{
		            // 根据名字对应到相应的系列
		            name: '销售额(元)',
		            barWidth : 50,
		            data: data.series
		        }]
		    });
		}
	});
	
//	jQuery.ajax({
//		url : encodeURI(urlArea),
//		type : 'get',
//		dataType : 'json',
//		contentType : 'application/json;charset=utf-8',
//		success : function(data) {
//			// 指定图表的配置项和数据
//			myAreaChart.setOption({
//		        series: [{
//		              name: '销售额',
//		              type: 'pie',
//		              radius: '55%',
//		              data:data.data
//		        }]
//		    });
//		}
//	});
	
	jQuery.ajax({
		url : encodeURI(urlIndustry),
		type : 'get',
		data:queryData,
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			// 指定图表的配置项和数据
			myIndustryChart.setOption({
		        xAxis: {
		            data: data.Axis
		        },
		        series: [{
		            // 根据名字对应到相应的系列
		            name: '销售额(元)',
		            data: data.series,
		            barWidth : 50
		        }]
		    });
		}
	});
	
	
	
	jQuery.ajax({
		url : encodeURI(urlMyTrend),
		type : 'get',
		data:queryData,
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			// 指定图表的配置项和数据
			myTrendChart.setOption({
				xAxis : [
				            {
				                type : 'category',
				                boundaryGap : false,
				                data : data.Axis
				            }
				        ],
		        series : [
		            {
		                name:'合同金额',
		                type:'line',
		                data:data.seriesSumTotal,
		                markLine : {
		                    data : [
		                        {type : 'average', name: '平均值'}
		                    ]
		                }
		            }
		        ]
		    });
		}
	});
	
	jQuery.ajax({
		url : encodeURI(urlContractType),
		type : 'get',
		data:queryData,
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			// 指定图表的配置项和数据
			myContractTypeChart.setOption({
		        series: [{
		              name: '销售额',
		              type: 'pie',
		              radius: '55%',
		              data:data.data
		        }]
		    });
		}
	});
	//总体行业分析
	var mydate = new Date();
	queryData.beginDate = '2001-01-01';
	var enddate = "" + mydate.getFullYear() + "-";
	enddate += ((mydate.getMonth()+1)<10 ? '0'+(mydate.getMonth()+1) : (mydate.getMonth()+1)) + "-";
	enddate += (mydate.getDate()<10 ? '0'+mydate.getDate() : mydate.getDate());
	queryData.endDate = enddate;
	queryData.dateTimeType = 'createTime';
	jQuery.ajax({
		url : encodeURI(urlIndustry),
		type : 'get',
		data:queryData,
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			// 指定图表的配置项和数据
			myIndustryTotalChart.setOption({
		        xAxis: {
		            data: data.Axis
		        },
		        series: [{
		            // 根据名字对应到相应的系列
		            name: '销售额(元)',
		            data: data.series,
		            barWidth : 50
		        }]
		    });
		}
	});
	//统计总价-yry
	getSum();
	myContractDeptTypeChart.setOption({
        title: {
            text: '合同类型分析（部门）'
        },
        tooltip: {},
        series : [{
              name: '销售额',
              type: 'pie',
              radius: '55%',
              data:[],
              itemStyle:{ 
                  normal:{ 
                        label:{ 
                          show: true, 
                          formatter: '{b} : {d}%' 
                        }, 
                        labelLine :{show:true} 
                      } 
                  } 
        }]
    });
	//片区分析
    myAreaChart.setOption({
        title: {
            text: '片区分析（部门）',
            padding: 10,
        },
        tooltip: {},
        series : [{
              name: '销售额',
              type: 'pie',
              radius: '55%',
              data:[],
              itemStyle:{ 
                  normal:{ 
                        label:{ 
                          show: true, 
                          formatter: '{b} : {d}%' 
                        }, 
                        labelLine :{show:true} 
                      } 
                  } 
        }]
    });
}

//统计总价--yry
function getSum(){
	urlsum = window.rootPath+ '/ui/contractviewindex/getPageSum?type=1';
	var nameDate = jQuery('#dateTimeType').val();
	var startDate = jQuery('#beginDate').val();
	var endDate = jQuery('#endDate').val();
	if(nameDate=="createTime"){
		if(startDate) {
			urlsum += "&createTimeStartDate=" + startDate;
		}
		if(endDate) urlsum += "&createTimeEndDate=" + endDate;
	}
	if(nameDate=="signedDate"){
		if(startDate) urlsum += "&signedDateStartDate=" + startDate;
		if(endDate) urlsum += "&signedDateEndDate=" + endDate;
	}
	if(nameDate=="scheduleDate"){
		if(startDate) urlsum += "&scheduleDateStartDate=" + startDate;
		if(endDate)  urlsum += "&scheduleDateEndDate=" + endDate;
	}
	$.ajax({
        type: "GET", 
        dataType: 'json',
        async: false, 
        url: encodeURI(urlsum),
        success: function(data) {
        	jQuery('#sum').val(data.sum);
        }
	});
}

//查询类型 1：部门 2：片区 3：行业 4：趋势 5：产品类型 6：合同类型
function openContractList(type,value,value1){
	var url = window.rootPath + "/ui/contractviewindex";
	if(type == 1){
		url += "?deptName=" +value;
	}else if(type == 2){
		url += "?deptName=" +value + "&areaName="+value1;
	}else if(type == 3){
		url += "?industryName=" +value;
	}else if(type == 4){
		var beginDate = value.split("年")[0] + "-" + ((value.split("年")[1].split("月")[0] < 10) ? "0"+value.split("年")[1].split("月")[0] : value.split("年")[1].split("月")[0]) + "-01";
		var endDate = value.split("年")[0] + "-" + (((parseInt(value.split("年")[1].split("月")[0])+1) < 10) ? "0"+(parseInt(value.split("年")[1].split("月")[0])+1) : (parseInt(value.split("年")[1].split("月")[0])+1)) + "-01";
		if(value.split("年")[1].split("月")[0] == 12){//要进一个月
			endDate = parseInt(value.split("年")[0])+1 + "-01-01";
		}
		url += "?beginDate=" +beginDate + "&endDate="+endDate;
	}else if(type == 5){
		
	}else if(type == 6){
		if(value1 != null)
			url += "?deptName=" +value+ "&contractType="+ value1;
		else
			url += "?contractType="+ value;
	}
	
	if(type != 4){
		url += "&beginDate=" + jQuery('#beginDate').val() + "&endDate=" + jQuery('#endDate').val();
	}
	url += "&dateTimeType=" + jQuery('#dateTimeType').val();
	window.open(url);
}